// 页面切换功能
function switchContent(section) {
    console.log('Switching to content:', section);

    // 获取所有内容区域
    const contentSections = document.querySelectorAll('.content-section');

    // 隐藏所有内容区域
    contentSections.forEach(el => {
        el.style.display = 'none';
        el.classList.remove('active');
    });

    // 显示选中的内容区域
    const selectedSection = document.getElementById(section + 'Section');
    if (selectedSection) {
        selectedSection.style.display = 'block';
        selectedSection.classList.add('active');
        console.log('Showing section:', section + 'Section');

        // 特殊处理不同类型的内容
        switch(section) {
            case 'message':
                // 如果有留言板初始化函数，调用它
                if (typeof initMessageBoard === 'function') {
                    console.log('正在初始化留言板...');
                    initMessageBoard();
                } else {
                    console.error('留言板初始化函数未找到');
                }
                break;
            case 'dashboard':
                // 触发窗口resize事件以确保图表正确渲染
                window.dispatchEvent(new Event('resize'));
                break;
            case 'graph':
                // 如果有图谱初始化函数，调用它
                if (typeof initGraph === 'function') {
                    initGraph();
                }
                break;
            case 'nodeData':
                // 如果有节点数据初始化函数，调用它
                const nodeTypeSelect = document.getElementById('nodeTypeSelect');
                if (nodeTypeSelect && nodeTypeSelect.value && typeof loadNodeData === 'function') {
                    loadNodeData();
                }
                break;
            case 'profile':
                // 加载个人资料页面的脚本
                if (!document.querySelector('script[src="/static/js/profile.js"]')) {
                    const script = document.createElement('script');
                    script.src = '/static/js/profile.js';
                    document.body.appendChild(script);
                }
                break;
        }
    } else {
        console.error('Section not found:', section + 'Section');
    }

    // 更新导航栏激活状态
    const navLinks = document.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('onclick')?.includes(section)) {
            link.classList.add('active');
            console.log('Activated nav link for:', section);
        }
    });
}

// 搜索功能
function search() {
    const query = document.getElementById('searchInput').value;
    if (!query.trim()) return;

    fetch(`/api/search?name=${encodeURIComponent(query)}`)
        .then(response => response.json())
        .then(function(data) {
            if (!data.success) {
                alert(data.message);
                return;
            }

            switchContent('graph');

            const detailsContent = document.getElementById('detailsContent');
            detailsContent.innerHTML = '<h4 class="mb-4">搜索结果</h4>';

            data.data.forEach(item => {
                const properties = item.properties;
                const div = document.createElement('div');
                div.innerHTML = `
                    <div class="p-4 bg-white rounded-lg shadow mb-3">
                        <h3 class="text-xl font-bold mb-2">${properties.name}</h3>
                        <p class="text-gray-700">${properties.description || '暂无描述'}</p>
                    </div>
                `;
                detailsContent.appendChild(div);
            });
        })
        .catch(error => {
            console.error('搜索出错:', error);
            alert('搜索过程中出现错误，请稍后重试');
        });
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", function() {
    // 初始化显示dashboard界面
    switchContent('dashboard');

    // 为搜索框添加回车事件监听
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                search();
            }
        });
    }
});